package com.ruoyi.system.util;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.SysCertificateInfo;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @ClassName: LicenseGenerator
 * @Description: 证书内容生成工具
 *
 * @author linjinkun
 * @date 2023/10/24
 */
public class LicenseGenerator {

    public static byte[] function(SysCertificateInfo sysCertificateInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = sdf.format(sysCertificateInfo.getCertificateDeadline());
        JSONObject localJsonObject = new JSONObject();
        localJsonObject.put("endtime", endTime);
        //host或者mac设置
        String TYPE_PRE = "host认证";
        if (TYPE_PRE.equals(sysCertificateInfo.getCertificateCheckType())) {
            String appHost = sysCertificateInfo.getCertificateCheckAddress();
            localJsonObject.put("apphost", appHost);
        } else {
            String appMac = sysCertificateInfo.getCertificateCheckAddress();
            localJsonObject.put("appmac", appMac);
        }
        String source = localJsonObject.toString();
        System.out.println("\r加密前文字：\r\n" + source);
        byte[] data = source.getBytes();
        byte[] encodedData;
        try {
            Map<String, Object> keyMap = RSAUtils.genKeyPair();
            String publicKey = RSAUtils.getPublicKey(keyMap);
            String privateKey = RSAUtils.getPrivateKey(keyMap);
            encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
            String encodedDatastr = LicenseUtils.bytesToString(encodedData);
            String sign = RSAUtils.sign(encodedData, privateKey);
            // 写入本地的内容： 签名 + 加密后的密文
            String content = publicKey + "$$" + sign + encodedDatastr;
            System.out.println("\r文件内容：\r\n" + content);
            return content.getBytes();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
